package com.module_live.fragment.coachstudy;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.LinearLayout;

import com.google.gson.Gson;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.utils.time_deal.TimeUtils;
import com.lib.fastkit.views.dialog.zenhui.AlertDialog;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.upload.QiNiuUploadTask;
import com.lib.utls.upload.initerface.FileUploadListener;
import com.module_live.R;
import com.module_live.R2;
import com.module_live.activity.CoachStudyLivingActivity;
import com.module_live.bean.IMBean;
import com.module_live.bean.coachstudy.ApplyHandBean;
import com.module_live.bean.coachstudy.UploadHomeWorkImgBean;
import com.module_live.fragment.coachstudy.workrecord.WorkRecordMainFragment;
import com.module_live.utils.socket.IMSocketUtils;
import com.module_live.view.StudentFinsihedWorkPopup;
import com.module_live.view.StudentListAndGiftPopup;
import com.module_live.view.StudentRequestListPopup;
import com.module_live.view.StudySetWorkPopup;

import butterknife.BindView;
import butterknife.OnClick;


@SuppressLint("ValidFragment")
public class StudyControlMenuFragment extends BaseAppFragment {

    @BindView(R2.id.lin_student_seeplan)
    LinearLayout linStudentSeeplan;
    @BindView(R2.id.lin_student_finish)
    LinearLayout linStudentFinish;
    @BindView(R2.id.lin_student_record)
    LinearLayout linStudentRecord;
    @BindView(R2.id.lin_student_apply)
    LinearLayout linStudentApply;
    @BindView(R2.id.lin_student_camera)
    LinearLayout linStudentCamera;
    @BindView(R2.id.lin_student_list)
    LinearLayout linStudentList;
    @BindView(R2.id.lin_student_contain)
    LinearLayout linStudentContain;

    @BindView(R2.id.lin_teacher_set)
    LinearLayout linTeacherSet;
    @BindView(R2.id.lin_teacher_see)
    LinearLayout linTeacherSee;
    @BindView(R2.id.lin_teacher_record)
    LinearLayout linTeacherRecord;
    @BindView(R2.id.lin_teacher_applylist)
    LinearLayout linTeacherApplylist;
    @BindView(R2.id.lin_teacher_list)
    LinearLayout linTeacherList;
    @BindView(R2.id.lin_teacher_exit)
    LinearLayout linTeacherExit;
    @BindView(R2.id.lin_teacher_contain)
    LinearLayout linTeacherContain;

    private String identity = "";
    private String token = "";

    private View parentView;

    //设置、显示作业
    StudySetWorkPopup setWorkPopup;

    //展示学生已经上交的作业
    StudentFinsihedWorkPopup finishedWorkPopup;

    //显示学生提交的举手申请
    StudentRequestListPopup requestListPopup;

    //学生列表及获赞和鲜花弹出框
    StudentListAndGiftPopup giftPopup;

    private IMBean imBean;
    private Gson gson;
    //发送接收消息(所有人)
    public static final int ACTION_TYPE1 = 1;
    //学生申请语音(老师)
    public static final int ACTION_TYPE2 = 2;
    //学生申请视频(老师)
    public static final int ACTION_TYPE3 = 3;
    //老师对申请进行操作(语音，视频)(指定学生)
    public static final int ACTION_TYPE4 = 4;
    //学生加入(所有人)
    public static final int ACTION_TYPE5 = 5;
    //学生离开(所有人)
    public static final int ACTION_TYPE6 = 6;
    //直播间用户列表(所有人)
    public static final int ACTION_TYPE7 = 7;
    //学生取消视频，语音(系统)
    public static final int ACTION_TYPE8 = 8;
    //更新聊天室用户信息(所有人)
    public static final int ACTION_TYPE9 = 9;
    //手动获取直播间列表(系统)
    public static final int ACTION_TYPE10 = 10;

    //老师关闭学生的语音、视频(返回9、11)
    public static final int ACTION_TYPE11 = 11;

    //老师下课
    public static final int ACTION_TYPE12 = 12;

    //文字
    public static final int MESSAGE_TYPE1 = 1;
    //图片
    public static final int MESSAGE_TYPE2 = 2;

    private String roomName;

    private String userName;

    private String userPhone;

    private String userIcon;

    @SuppressLint("ValidFragment")
    public StudyControlMenuFragment(String roomName) {
        this.roomName = roomName;
    }

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        identity = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserIdentity();
        token = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken();

        //通过身份来判断显示不同控制菜单
        if (StringUtil.isNotEmpty(identity, true)) {
            if ("1".equals(identity)) {
                linStudentContain.setVisibility(View.GONE);
            } else if ("2".equals(identity)) {

                linTeacherContain.setVisibility(View.GONE);
                linStudentContain.setVisibility(View.VISIBLE);
            }
        }

        initPopupView();

        userName = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserName();
        userIcon = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserHeadUrl();
        userPhone = SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone();

        gson = new Gson();

        CoachStudyLivingActivity.imSocketUtils.setIMSocketListener(imSocketListener);

    }

    private void initPopupView() {

        setWorkPopup = new StudySetWorkPopup(getActivity());

        finishedWorkPopup = new StudentFinsihedWorkPopup(getActivity());
        finishedWorkPopup.setFinishedWorkOperateListener(new StudentFinsihedWorkPopup.FinishedWorkOperateListener() {
            @Override
            public void onTeacherSetAudio(int type) {

                if (listener != null) {
                    listener.onTeacherAddRecord(type);
                }
            }
        });

        requestListPopup = new StudentRequestListPopup(getActivity());
        requestListPopup.setRequestVoicePopupListener(new StudentRequestListPopup.RequestVoicePopupListener() {
            @Override
            public void onAllowVoice(String userPhone) {

            }

            @Override
            public void onRefuseVoice(String userPhone) {

            }
        });

        giftPopup = new StudentListAndGiftPopup(getActivity());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_study_control;
    }


    @OnClick({R2.id.lin_teacher_set, R2.id.lin_teacher_see, R2.id.lin_teacher_list,
            R2.id.lin_teacher_applylist, R2.id.lin_teacher_record, R2.id.lin_teacher_exit,

            R2.id.lin_student_seeplan, R2.id.lin_student_finish, R2.id.lin_student_list,
            R2.id.lin_student_apply, R2.id.lin_student_record, R2.id.lin_student_camera
    })
    public void onViewClicked(View view) {
        int i = view.getId();
        parentView = view;

        if (i == R.id.lin_teacher_set) {//老师设置作业内容及时间----------0

            if (listener != null) {
                listener.onSetHomeWorkTime();
            }
            //显示设置作业popup
            setWorkPopup.updateSetWorkData(parentView);
            setWorkPopup.showAnswerPopuPopu(parentView);

        } else if (i == R.id.lin_teacher_see) {//老师查看学生提交作业----------0

            //显示作业列表popup
            if (listener != null) {
                listener.onSeeFinishedWork();
            }
            finishedWorkPopup.updateFinishedWorkData(parentView);
            finishedWorkPopup.showAnswerPopuPopu(parentView);

        } else if (i == R.id.lin_teacher_applylist) {//老师查看举手列表----------0

            //显示举手列表popup
            if (listener != null) {
                listener.onApplyList();
            }

            requestListPopup.updateRequestListData();
            requestListPopup.showAnswerPopuPopu(parentView);

        } else if (i == R.id.lin_teacher_record) {//老师查看作业记录----------0

//            if (listener != null) {
//                listener.onSeeRecordList();
//            }
            showWorkRecord();

        } else if (i == R.id.lin_teacher_exit) {//老师下课----------1

            if (listener != null) {
                listener.onTeacherCloseRoom();
            }
//            showSex();

        } else if (i == R.id.lin_teacher_list) {//老师查看学生列表----------1

//            if (listener != null) {
//                listener.onTeacherCloseRoom();
//            }
            giftPopup.updateStudentListData();
            giftPopup.showAnswerPopuPopu(parentView);

        } else if (i == R.id.lin_student_seeplan) {//学生查看作业设置内容----------0

            //显示设置作业popup
            setWorkPopup.updateSetWorkData(parentView);
            setWorkPopup.showAnswerPopuPopu(parentView);

        } else if (i == R.id.lin_student_finish) {//学生提交作业----------1

//            if (listener != null) {
//                listener.onStudentUploadWork();
//            }

//            requestOpenVoice();

            if (listener != null) {
                listener.onStudentTakePhoto(0);
            }

        } else if (i == R.id.lin_student_apply) {//学生举手----------1

            requestOpenVoice();
            //发送举手请求至服务器
            sendStudentApplyHandToService();

        } else if (i == R.id.lin_student_record) {//学生查看作业记录----------0

            if (listener != null) {
                listener.onStudentSeeRecord();
            }
//            showNick();

            showWorkRecord();

        } else if (i == R.id.lin_student_camera) {//学生申请下课----------1

            if (listener != null) {
                listener.onStudentSwitchCamera();
            }
//            showSex();

        } else if (i == R.id.lin_student_list) {//学生查看学生列表----------1

//            if (listener != null) {
//                listener.onStudentApplyLeave();
//            }
            giftPopup.updateStudentListData();
            giftPopup.showAnswerPopuPopu(parentView);
        }
    }

    //dialog_student_luckydraw  fragment_lucky
    StudentLuckyDrawWebFragment sexFragment;

    private void showSex() {
        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setContentView(R.layout.dialog_student_luckydraw)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (sexFragment != null) {
                            getActivity().getSupportFragmentManager().beginTransaction().remove(sexFragment).commit();
                            sexFragment = null;
                        }
                    }
                })
                .fullWidth()
                .addDefaultAnimation()
                .show();

        sexFragment = (StudentLuckyDrawWebFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_lucky);

    }

    WorkRecordMainFragment nickNameFragment;

    private void showWorkRecord() {

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setContentView(R.layout.popup_study_record)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (nickNameFragment != null) {
                            getActivity().getSupportFragmentManager().beginTransaction().remove(nickNameFragment).commit();
                            nickNameFragment = null;
                        }
                    }
                })
                .fullWidth()
                .addDefaultAnimation()
                .show();

        nickNameFragment = (WorkRecordMainFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_record);
    }

    public interface StudyControlMenuFragmentListener {

        void onSetHomeWorkTime();//设置作业的内容以及时间

        void onSeeFinishedWork();//查看学生提交的作业

        void onApplyList();//查看举手列表

        void onSeeRecordList();//查看作业历史记录

        void onTeacherCloseRoom();//老师下课

        void onStudentSwitchCamera();//学生切换摄像头

        void onStudentWorkList();//查看作业安排列表

        void onStudentUploadWork();//学生上传作业

        void onStudentApply();//学生举手申请语音

        void onStudentSeeRecord();//学生查看作业记录

        void onUploadImgSuccess();//上传图片成功

        void onAllowVoice(String userPhone);

        void onRefuseVoice(String userPhone);


        //--------------10-28加入，学生暂时关闭摄像头，老师暂时关闭语音

        void onStudentTakePhoto(int type);//学生需要拍照，则先需要关闭摄像头采集

        void onTeacherAddRecord(int type);//老师需要语音录入，暂时先取消发布

    }


    private StudyControlMenuFragmentListener listener;

    public void setStudyControlMenuFragmentListener(StudyControlMenuFragmentListener studyControlMenuFragmentListener) {

        this.listener = studyControlMenuFragmentListener;

    }


    //=============================================================================================
    //==============================================================================图片选择=======
    //=============================================================================================

    /**
     * 上传ppt和图片操作
     * MainRoomActivity调用
     * type String类型，区别图片和ppt
     * <p>
     * Bitmap用于判断图片宽高以及比例
     * course_id用于上传PPT课件
     * compressPath用于上传本地文件到七牛
     * pageIndex当前白板索引，用于获取当前白板场景，判断上传图片的显示大小
     *
     * @param compressPath
     */
    public void upLoadImage(String compressPath) {

        QiNiuUploadTask qiNiuUploadTask = new QiNiuUploadTask(getActivity());
        qiNiuUploadTask.setFileUploadListener(new FileUploadListener() {
            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onSuccess(String s) {

                if ("".equals(s) || null == s || "null".equals(s) || s.length() < 5) {

                    showToast("上传失败，请重新选择!");
                } else {

                    String urlHead = SharedPreferenceManager.getInstance(getContext()).getUserCache().getQiNiuUrl();
                    LogUtil.e("获取的路径：" + urlHead + s);
                    //上传图片到服务器
                    sendHomeWorkImgToService(s);
                }
            }

            @Override
            public void onError(String e) {

                Looper.prepare();
                showToast("图片上传失败");
                Looper.loop();// 进入loop中的循环，查看消息队列
            }
        });
        qiNiuUploadTask.execute(compressPath, SharedPreferenceManager.getInstance(getActivity()).getUserCache().getQiNiuToken());

    }

    private void sendHomeWorkImgToService(String s) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "STUDENT_COMPLETED_ASSIGNMENT")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("course_id", CoachStudyLivingActivity.course_id)
                .addParam("completed_assignment_image", s)
                .execute(new HttpNormalCallBack<UploadHomeWorkImgBean>() {
                    @Override
                    public void onSuccess(UploadHomeWorkImgBean result) {
                        if (CodeUtil.CODE_200 == result.getCode()) {
                            LogUtil.e("家庭作业上传服务器成功");
                            if (listener != null) {
                                listener.onUploadImgSuccess();
                                listener.onStudentTakePhoto(1);
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }


    //-----------------------------------------------------------------------------消息监听
    IMSocketUtils.IMSocketListener imSocketListener = new IMSocketUtils.IMSocketListener() {
        @Override
        public void onOpen() {

        }

        @Override
        public void onMessage(String json) {

            try {
                imBean = MGson.newGson().fromJson(json, IMBean.class);
            } catch (Exception e) {

                showLog(e.getMessage());

            }

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    dealMessage();
                }
            });

        }


        @Override
        public void onClosed() {

        }

        @Override
        public void onClosing() {

        }

        @Override
        public void onFailure() {

        }
    };

    private void dealMessage() {
        int type = imBean.getActionType();
        switch (type) {
            case ACTION_TYPE1: {
                //发送接收消息

//                CoachStudyLivingActivity.messageList.add(imBean);
                break;
            }

            case ACTION_TYPE2: {
                //学生申请语音

//                requestListPopup.addRequest(imBean);
//                requestListPopup.showAnswerPopuPopu(parentView);

                break;
            }

            case ACTION_TYPE3: {
                //学生申请视频

//                CoachStudyLivingActivity.roomControlFragment.addRequest(imBean);
//                CoachStudyLivingActivity.roomControlFragment.showRequestPopu();


                break;
            }
            case ACTION_TYPE4: {
                //老师对申请进行操作(语音，视频)

                int type4 = imBean.getObject().getType();

                if (type4 == 2) {
                    //语音
                    String action = imBean.getObject().getAction();

                    if (action.equals("1")) {
                        //同意
                        showToast("申请成功！");

                        if (listener != null) {
                            listener.onAllowVoice(imBean.getObject().getUserPhone());
                        }
                    }
                    if (action.equals("0")) {
                        //不同意
                        showToast("申请失败！");

                    }

                }

                break;
            }

            case ACTION_TYPE5: {
                //学生加入

//                if (listener != null) {
//                    listener.onUserJoinRoom(imBean.getObject());
//                }


                break;
            }

            case ACTION_TYPE6: {
                //学生离开
//                if (listener != null) {
//                    listener.onUserLeftRoom(imBean.getObject());
//                }

                break;
            }

            case ACTION_TYPE7: {
                //直播间用户列表

//                if (listener != null) {
//                    listener.onGetUserList(imBean.getObject().getUserList());
//                }


                break;
            }

            case ACTION_TYPE8: {
                //学生取消视频，语音


                break;
            }


            case ACTION_TYPE9: {
                //更新聊天室

//                if (listener != null) {
//                    listener.onUpdateUserInfo(imBean.getObject());
//                }


                break;
            }
            case ACTION_TYPE11: {
                //更新指定学生的麦克风、摄像头状态

//                if (listener != null) {
//                    listener.onUpdateStudentVoiceCameraInfo(imBean.getObject());
//                }


                break;
            }

        }
    }

    /**
     * 学生请求打开麦克风
     */
    public void requestOpenVoice() {
        IMBean imBean = new IMBean();
        imBean.setActionType(ACTION_TYPE2);
        IMBean.ObjectBean objectBean = new IMBean.ObjectBean();
        objectBean.setActionTag(TimeUtils.getNowTimestamp() + "");
        objectBean.setUserName(userName);
        objectBean.setUserIcon(userIcon);
        objectBean.setRoomName(roomName);
        objectBean.setUserPhone(userPhone);
        imBean.setObject(objectBean);
        String json = MGson.newGson().toJson(imBean);
        showLog(json);

        CoachStudyLivingActivity.imSocketUtils.sendMessage(json);
    }

    /**
     * 老师处理是否打开麦克风
     */
    public void requestBackOpenVoice(boolean b, String studentPhone) {
        IMBean imBean = new IMBean();
        imBean.setActionType(ACTION_TYPE4);
        IMBean.ObjectBean objectBean = new IMBean.ObjectBean();

        objectBean.setUserPhone(studentPhone);
        objectBean.setType(2);
        if (b) {
            objectBean.setAction("1");
        } else {
            objectBean.setAction("0");
        }

        objectBean.setRoomName(roomName);
        imBean.setObject(objectBean);
        String json = MGson.newGson().toJson(imBean);
        showLog(json);
        CoachStudyLivingActivity.imSocketUtils.sendMessage(json);
    }


    public void sendStudentApplyHandToService() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "STUDENTS_RAISE_THEIR_HANDS")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("course_id", CoachStudyLivingActivity.course_id)
                .addParam("raise_hands", 1)
                .execute(new HttpNormalCallBack<ApplyHandBean>() {
                    @Override
                    public void onSuccess(ApplyHandBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            LogUtil.e("举手成功");

                            if (listener != null) {
                                listener.onStudentApply();
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

}
